package com.sec.etech.form.cust.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ZipUtil;
import com.alibaba.fastjson.JSONObject;
import com.sec.etech.form.cust.service.EtechGenCodeService;
import org.openbpm.base.api.aop.annotion.CatchErr;
import org.openbpm.base.api.response.impl.ResultMsg;
import org.openbpm.base.core.util.StringUtil;
import org.openbpm.base.rest.ControllerTools;
import org.openbpm.base.rest.util.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Map;

@RestController
@RequestMapping({"/etech/formCodeGenerate/"})
public class EtechFormCodeGenerateController extends ControllerTools {
  @Autowired
  EtechGenCodeService etechGenCodeService;

  private static final String ROOT_PATH = "temp" + File.separator + "tempZip/genCode";

  @RequestMapping(value = {"genCode"}, method = {RequestMethod.POST})
  @CatchErr("生成失败")
  public ResultMsg exportExcel(HttpServletRequest request, HttpServletResponse response, @RequestParam("data") String data) throws Exception {
    JSONObject json = JSONObject.parseObject(data);
    Map<String, String> codes = this.etechGenCodeService.genCode(json);
    String zipPath = getWebContextPath() + ROOT_PATH;
    File file = null;
    try {
      for (Map.Entry<String, String> ent : codes.entrySet()) {
        String fileName = ent.getKey();
        String content = ent.getValue();
        String filePath = zipPath + File.separator + fileName;
        FileUtil.writeUtf8String(content, filePath);
      }
      file = ZipUtil.zip(zipPath);
      RequestUtil.downLoadFile(response, file);
    } catch (Exception e) {
      return ResultMsg.ERROR("生成异常:" + e.getLocalizedMessage());
    } finally {
      FileUtil.del(zipPath);
      FileUtil.del(file);
    }
    return null;
  }

  protected static String getWebContextPath() {
    // 增加容器环境支持
    String path = ClassUtil.getClassPath();
    if (path.indexOf("WEB-INF") != -1) {
      path = path.substring(0, path.lastIndexOf("WEB-INF"));
    } else if(path.indexOf("classes") != -1){
      path = path.substring(0, path.lastIndexOf("classes"));
    } else {
      path = System.getProperty("user.dir");
      if(StringUtil.isEmpty(path)){
        File tfile = new File("");
        try{
          path = tfile.getAbsolutePath();
        }catch (Exception e){
          path = System.getProperty("user.home");
        }
      }
    }
    path = StringUtil.trimSuffix(path, "/");
    return path;
  }
}
